package com.mrd.modules.attachment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.mrd.base.utils.DownloadUtils;
import com.mrd.base.utils.FileUtils;

/**
 * Created by han
 */
@Component("attachmentService")
public class LocalhostAttachmentImpl implements AttachmentService {

  @Value("${FILE_PATH}")
  private String filePath;

  @Override
  public String upload(MultipartFile multipartFile, String fileName) throws IOException {
    String type = FileUtils.getFileType(multipartFile.getOriginalFilename()).toLowerCase();
    return this.upload(multipartFile.getInputStream(), fileName, type);
  }

  @Override
  public String upload(File file, String fileName, String type) throws Exception {
    String fileNameRtn = this.getFileName(fileName, type);
    InputStream in = new FileInputStream(file);
    return this.upload(in, fileNameRtn, type);
  }

  @Override
  public void delete(String id) {
    String filePath = this.getPath() + id;
    FileUtils.deleteFile(filePath);
  }

  private String getFileName(String fileName, String type) {
    StringBuffer sb = new StringBuffer();
    sb.append("/");
    // sb.append(DateTimeUtils.format(new Date(),"yyyy-MM-dd"));
    // sb.append("/");
    sb.append(fileName);
    sb.append(".");
    sb.append(type);
    return sb.toString();
  }

  @Override
  public String upload(InputStream inputStream, String fileName, String type) throws IOException {
    String fileNameRtn = this.getFileName(fileName, type);
    FileUtils.saveFile(inputStream, filePath + fileNameRtn);
    return fileNameRtn;
  }

  @Override
  public String getPath() {
    StringBuffer sb = new StringBuffer();
    sb.append(filePath);
    sb.append("/");
    return sb.toString();
  }

  @Override
  public void download(String path, String fileName, HttpServletResponse response) {
    String filePath = this.getPath() + path;
    DownloadUtils.download(response, filePath, fileName);
  }

  @Override
  public File download(String id) {
    String filePath = this.getPath() + id;
    return new File(filePath);
  }

}
